﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace FksAutoTask
{
    public partial class frm_main : App_Code.WinClient
    {
        private int Proess_Nums_Has = 0;
        private int Proess_Nums_Yes = 0;
        Thread thread_run;

        public frm_main()
        {
            InitializeComponent();
        }

        private void 服务器及参数设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frm_param fp = new frm_param();
            fp.ShowDialog();
        }

        private void 添加任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frm_task fat = new frm_task();
            fat.Owner = this;
            fat.ShowDialog();
        }

        private void frm_main_Load(object sender, EventArgs e)
        {
            Init();
            Shows();
        }

        /// <summary>
        /// 初始化显示分组信息
        /// </summary>
        public void Shows()
        {
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
            string SQL = "select group_id from task group by group_id";

            DataSet myds = sqlobject.GetDataSet(SQL);
            if (myds != null && myds.Tables.Count > 0 && myds.Tables[0].Rows.Count > 0)
            {
                this.cb_group_id.Items.Clear();

                for (int i = 0; i < myds.Tables[0].Rows.Count; i++)
                    this.cb_group_id.Items.Add(myds.Tables[0].Rows[i][0]);
            }
        }

        /// <summary>
        /// 显示所有任务
        /// </summary>
        public void Dbind()
        {
            string _group_id = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.cb_group_id, "Text"));
            if (!string.IsNullOrEmpty(_group_id))
            {
                int Recount = 0;

                string where = "where 2>1";
                if (!string.IsNullOrEmpty(_group_id))
                    where += " and group_id='" + _group_id + "'";

                string _key = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.txt_Keys, "Text"));
                if (!string.IsNullOrEmpty(_key))
                    where += " and (name like '%" + _key + "%' or email like '%" + _key + "%' or mobile like '%" + _key + "%')";

                string _status = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.cb_status, "Text"));
                if (!string.IsNullOrEmpty(_status) && _status != "=所有=")
                    where += " and (case status when 1 then '已发送' else '未发送' end)='" + _status + "'";


                Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
                string fileds = "*,(case status when 1 then '已发送' else '未发送' end) status_name";
                string SQL = sqlobject.GetSelect_SQL(this.fksPager1.PageIndex, this.fksPager1.PageSize, fileds, "task", where, "", "", "order by id desc");

                DataSet myds = sqlobject.GetDataSet(SQL);
                DataSet myds_pageer = sqlobject.GetDataSet("select count(0) from task " + where);
                if (myds_pageer != null && myds_pageer.Tables.Count > 0 && myds_pageer.Tables[0] != null && myds_pageer.Tables[0].Rows.Count > 0)
                    Recount = Convert.ToInt32(myds_pageer.Tables[0].Rows[0][0]);

                Fks.Common.Win.InvokerUntity.Set(this.Ilist, "AutoGenerateColumns", false);
                Fks.Common.Win.InvokerUntity.Set(this.Ilist, "DataSource", myds.Tables[0]);
                Fks.Common.Win.InvokerUntity.Set(this.fksPager1, "RecordCount", Recount);
            }
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            Dbind();
        }

        private void fksPager1_PageIndexChanged(object sender, EventArgs e)
        {
            Dbind();
        }

        private void btn_Run_Click(object sender, EventArgs e)
        {
            if (this.cb_group_id.Text.Equals(""))
            {
                this.cb_group_id.Focus();
                MessageBox.Show("请选择分组编号！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
                string SQL = "select * from param";

                DataSet myds = sqlobject.GetDataSet(SQL);
                if (myds != null && myds.Tables.Count > 0 && myds.Tables[0] != null && myds.Tables[0].Rows.Count > 0)
                {
                    if (thread_run == null || thread_run.ThreadState == ThreadState.Stopped || thread_run.ThreadState == ThreadState.Unstarted)
                    {
                        thread_run = new Thread(Run);
                        thread_run.Start();

                        //启用时间校验
                        this.timer1.Enabled = true;
                        this.timer1.Interval = 1000;
                    }
                    else
                        MessageBox.Show("线程忙！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("请先配置服务器的发件信息！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// 线程处理任务的方法
        /// </summary>
        void Run()
        {
            Fks.Common.Win.InvokerUntity.Set(this.btn_Run, "Enabled", false);

            Proess_Nums_Has = 0;
            Proess_Nums_Yes = 0;

            //1.获得参数
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
            string SQL = "select * from param";

            DataSet myds = sqlobject.GetDataSet(SQL);
            if (myds != null && myds.Tables.Count > 0 && myds.Tables[0] != null && myds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = myds.Tables[0].Rows[0];
                string _server_type = dr["server_type"].ToString();
                string _server = dr["email_server"].ToString().Split(':')[0];
                int _port = 25;
                try
                {
                    _port = Convert.ToInt32(_server.Split(':')[1]);
                }
                catch
                { }

                string _username = dr["email_user"].ToString();
                string _userpwd = dr["email_pwd"].ToString();
                string _form_email = dr["send_email"].ToString();
                string _cc_email = dr["cc_email"].ToString();
                bool _enable_ssl = Convert.ToBoolean(dr["enable_ssl"]);
                string _template_title = dr["email_title"].ToString();
                string _template_body = dr["email_body"].ToString();
                int _split = Convert.ToInt32(dr["split"]);

                string _group_id = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.cb_group_id, "Text"));

                string sql = "select * from task where group_id='" + _group_id + "' and status=0";
                DataSet myds_row = sqlobject.GetDataSet(sql);
                if (myds_row != null && myds_row.Tables.Count > 0 && myds_row.Tables[0] != null && myds_row.Tables[0].Rows.Count > 0)
                {
                    Proess_Nums_Has = myds_row.Tables[0].Rows.Count;
                    for (int i = 0; i < myds_row.Tables[0].Rows.Count; i++)
                    {
                        string _id = myds_row.Tables[0].Rows[i]["id"].ToString();

                        if (Send_Email(_group_id, _id, _server_type, _server, _port, _username, _userpwd, _form_email, _cc_email, _enable_ssl, _template_title, _template_body))
                            Proess_Nums_Yes++;

                        //停留指定的时间 
                        Thread.Sleep(_split * 1000);
                    }

                    Dbind();
                }
            }


            Fks.Common.Win.InvokerUntity.Set(this.btn_Run, "Enabled", true);
        }

        bool Send_Email(string group_id, string id, string server_type, string server, int ports, string username, string userpwd, string form_email, string cc_email, bool enable_ssl, string _template_title, string _template_body)
        {
            bool result = false;
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();

            string sql = "select * from task where id='" + id + "' and group_id='" + group_id + "'";
            DataSet myds_row = sqlobject.GetDataSet(sql);
            if (myds_row != null && myds_row.Tables.Count > 0 && myds_row.Tables[0] != null && myds_row.Tables[0].Rows.Count > 0)
            {
                if (myds_row.Tables[0].Rows[0]["status"].ToString() == "0")
                {
                    string _to_emial = myds_row.Tables[0].Rows[0]["email"].ToString();

                    if (!string.IsNullOrEmpty(_to_emial))
                    {
                        string _title = format_title(id, _template_title);
                        string _body = format_body(id, _template_body);

                        string error = string.Empty;
                        if (server_type.ToLower() == "smtp")
                        {
                            if (Fks.Common.Lib.EmailUntity.Smtp.Send(server, ports, username, userpwd, enable_ssl, _to_emial, form_email, _body, _title, _title, string.Empty, cc_email, string.Empty, true, out error))
                            {
                                string sql_update = "update task set status=1 where id='" + id + "'";
                                if (sqlobject.Exec(sql_update) > 0)
                                    result = true;
                                else
                                    Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, "系统错误！");
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(error))
                                {
                                    string sql_update = "update task set result='" + error + "' where id='" + id + "'";
                                    if (sqlobject.Exec(sql_update) == 0)
                                        Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, "系统错误！");
                                }
                            }
                        }
                        else if (server_type.ToLower() == "exchange")
                        {
                            if (Fks.Common.Lib.EmailUntity.Exchange.Send(server, ports, username, userpwd, _to_emial, _title, _body, string.Empty, true, out error))
                            {
                                string sql_update = "update task set status=1 where id='" + id + "'";
                                if (sqlobject.Exec(sql_update) > 0)
                                    result = true;
                            }
                            else
                                Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, error);
                        }
                    }
                }
            }

            return result;
        }

        string format_title(string id, string template_title)
        {
            //$group_id$=日期，$name$=姓名，$body$=工资正文
            string result = string.Empty;
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();

            string sql = "select * from task where id='" + id + "'";
            DataSet myds_row = sqlobject.GetDataSet(sql);
            if (myds_row != null && myds_row.Tables.Count > 0 && myds_row.Tables[0] != null && myds_row.Tables[0].Rows.Count > 0)
            {
                string _name = myds_row.Tables[0].Rows[0]["name"].ToString();
                string _group_id = myds_row.Tables[0].Rows[0]["group_id"].ToString();

                result = template_title.Replace("$group_id$", _group_id);
                result = result.Replace("$name$", _name);
                result = result.Replace("$body$", string.Empty);
            }

            return result;
        }

        string format_body(string id, string template_body)
        {
            //$group_id$=日期，$name$=姓名，$body$=工资正文
            string result = string.Empty;
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();

            string sql = "select * from task where id='" + id + "'";
            DataSet myds = sqlobject.GetDataSet(sql);
            if (myds != null && myds.Tables.Count > 0 && myds.Tables[0] != null && myds.Tables[0].Rows.Count > 0)
            {
                string _group_id = myds.Tables[0].Rows[0]["group_id"].ToString();
                string _month = myds.Tables[0].Rows[0]["month"].ToString();
                string _name = myds.Tables[0].Rows[0]["name"].ToString();

                #region 合并内容

                string _body_str = string.Empty;
                string sql_list = "select * from task_list where id='" + id + "'";
                DataSet myds_list = sqlobject.GetDataSet(sql_list);
                if (myds_list != null && myds_list.Tables.Count > 0 && myds_list.Tables[0] != null && myds_list.Tables[0].Rows.Count > 0)
                {
                    string _table = "<table border=\"0\" cellspacing=\"1\" cellpadding=\"3\" bgcolor=\"#ccc\" border=\"1\">{0}</table>";
                    string _head = string.Empty;
                    string _row = string.Empty;

                    /* 模向模式
                     * 
                    //主任务
                    _head += "<td bgcolor=\"#f0f0f0\">姓名</td>";
                    _row += "<td bgcolor=\"#fff\">" + _name + "</td>";

                    //明细
                    for (int i = 0; i < myds_list.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr_list = myds_list.Tables[0].Rows[i];

                        _head += "<td bgcolor=\"#f0f0f0\">" + dr_list["table_name"].ToString() + "</td>";
                        _row += "<td bgcolor=\"#fff\">" + dr_list["table_value"].ToString() + "</td>";
                    }

                    _head = "<tr>" + _head + "</tr>";
                    _row = "<tr>" + _row + "</tr>";
                     * 
                     */

                    //坚向模式

                    //主任务
                    _row += "<tr>";
                    _row += "<td bgcolor=\"#f0f0f0\">月份</td>";
                    _row += "<td bgcolor=\"#ffffff\">" + _month + "</td>";
                    _row += "</tr>";

                    _row += "<tr>";
                    _row += "<td bgcolor=\"#f0f0f0\">姓名</td>";
                    _row += "<td bgcolor=\"#ffffff\">" + _name + "</td>";
                    _row += "</tr>";

                    //明细
                    for (int i = 0; i < myds_list.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr_list = myds_list.Tables[0].Rows[i];

                        if (dr_list["table_value"].ToString() != "0" && !string.IsNullOrEmpty(dr_list["table_value"].ToString()))
                        {
                            _row += "<tr>";
                            _row += "<td bgcolor=\"#f0f0f0\">" + dr_list["table_name"].ToString() + "</td>";
                            _row += "<td bgcolor=\"#ffffff\">" + dr_list["table_value"].ToString() + "</td>";
                            _row += "</tr>";
                        }
                        else if (dr_list["table_name"].ToString() == "加班费")
                        {
                            _row += "<tr>";
                            _row += "<td bgcolor=\"#f0f0f0\">" + dr_list["table_name"].ToString() + "</td>";
                            _row += "<td bgcolor=\"#ffffff\">" + dr_list["table_value"].ToString() + "</td>";
                            _row += "</tr>";
                        }
                    }


                    _body_str = string.Format(_table, _head + _row);
                }

                #endregion

                //开始替换 
                result = Fks.Common.StringUntity.Str.TextToHtml(template_body);
                result = result.Replace("$group_id$", _group_id);
                result = result.Replace("$name$", _name);
                result = result.Replace("$body$", _body_str);
            }

            return result;
        }

        private void 清理任务CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
            Hashtable sql = new Hashtable();

            sql.Add("1_task", "delete from task");
            sql.Add("2_task_list", "delete from task_list");

            if (sqlobject.Commit(sql))
            {
                Shows();
                Dbind();
                MessageBox.Show("成功清理任务！", "系统提示！", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
                MessageBox.Show("系统错误！", "系统提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (thread_run.ThreadState == ThreadState.Stopped || thread_run.ThreadState == ThreadState.Unstarted)
            {
                this.timer1.Enabled = false;
                this.t_pb_fix.Visible = false;
                this.t_pb_text.Visible = false;

                MessageBox.Show("需要处理的任务：" + Proess_Nums_Has + "，已处理：" + Proess_Nums_Yes, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                this.t_pb_fix.Visible = true;
                this.t_pb_text.Visible = true;
                this.t_pb_fix.Maximum = Proess_Nums_Has;
                this.t_pb_fix.Value = Proess_Nums_Yes;

                this.t_pb_text.Text = "需要处理的任务：" + Proess_Nums_Has + "，已处理：" + Proess_Nums_Yes;
            }
        }

        private void Ilist_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string _id = this.Ilist.Rows[e.RowIndex].Cells[0].Value.ToString();

            frm_edit fe = new frm_edit();

            //显示任务信息
            fe.TaskId = _id;
            fe.Owner = this;
            fe.ShowDialog();
        }

        private void btn_Excel_Click(object sender, EventArgs e)
        {
            string _group_id = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.cb_group_id, "Text"));
            if (!string.IsNullOrEmpty(_group_id))
            {
                string where = "where 2>1";
                if (!string.IsNullOrEmpty(_group_id))
                    where += " and group_id='" + _group_id + "'";

                string _key = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.txt_Keys, "Text"));
                if (!string.IsNullOrEmpty(_key))
                    where += " and (name like '%" + _key + "%' or email like '%" + _key + "%' or mobile like '%" + _key + "%')";

                string _status = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.cb_status, "Text"));
                if (!string.IsNullOrEmpty(_status) && _status != "=所有=")
                    where += " and (case status when 1 then '已发送' else '未发送' end)='" + _status + "'";


                Fks.DataBase.SqlObject sqlobject = new Fks.DataBase.SqlObject();
                string fileds = "group_id 分组编号,month 月份,email 邮箱,name 姓名,result 反馈,(case status when 1 then '已发送' else '未发送' end) 状态";
                string SQL = sqlobject.GetSelect_SQL(0, fileds, "task", where, "", "", "order by id desc");

                DataSet myds = sqlobject.GetDataSet(SQL);

                if (myds != null && myds.Tables.Count > 0 && myds.Tables[0].Rows.Count > 0)
                {
                    string error = string.Empty;
                    string tmp_path = Application.UserAppDataPath + "\\tmp\\";
                    string tmp_file = "Ex_" + Fks.Common.RndUntity.GetRnd_Cu(6, 9);
                    Fks.Common.Lib.NOPIUntity.Export(myds.Tables[0], Fks.Common.EnumUntity.NopiTrager.Office2007, "Sheet1", tmp_path, string.Empty, tmp_file, out error);
                    Fks.Common.Win.ProcessUntity.Run_Program(tmp_path + tmp_file + ".xlsx");
                }
                else
                {
                    MessageBox.Show("数据集为空，无法导出！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                this.cb_group_id.Focus();
                MessageBox.Show("请选择分组编号！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}
